package com.briup.pts.service.impl;

import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.IndexRecord;
import com.briup.pts.mapper.AnimalMapper;
import com.briup.pts.mapper.IndexRecordMapper;
import com.briup.pts.service.IndexRecordService;
import com.briup.pts.util.AssertUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wy
 * @description
 * @data 2024/11/27  11:36
 */
@Service
@RequiredArgsConstructor
public class IndexRecordServiceImpl implements IndexRecordService {
    private final IndexRecordMapper mapper;
    private final AnimalMapper animalMapper;

    @Override
    public PageInfo<IndexRecord> pageQueryByCondition(Double startWeight, Double endWeight,
                                                        Integer pageNum, Integer pageSize) {
        // 使用过PageHelper开启分页
        try (Page<IndexRecord> ignored = PageHelper.startPage(pageNum, pageSize)) {
            // 根据条件查询数据库中的数据
            List<IndexRecord> indexRecords = mapper.queryPage(startWeight,endWeight);
            // 将查询的结果数据放入到PageInfo中返回
            return new PageInfo<>(indexRecords);
        }
    }

    @Override
    public void deleteById(Integer irdId) {
        mapper.deleteById(irdId);

    }

    @Override
    public void deleteByIdAll(List<Integer> ids) {
        mapper.deleteByIdAll(ids);
    }

    // @Transactional是Spring提供的声明式事务管理的注解，
    // 被标注了本注解的方法，会在方法执行之前自动开启事务，
    // 遇到异常（默认为运行时异常）时回滚
    // 方法执行没有问题，即提交事务
    @Transactional
    public void saveOrUpdate(IndexRecord indexRecord) {
        // 先根据动物id查询动物，确保动物存在
        String animalId = indexRecord.getIrdAnimalId();
        int count = animalMapper.countById(animalId);
        AssertUtil.isTrue(count == 1,
                ResultCode.ANIMAL_IS_NOT_EXISTS);
            mapper.addIndexRecord(indexRecord);
        // 再将动物体重、健康状态等数据同步到动物表中
        animalMapper.updateById(animalId,
                indexRecord.getIrdWeight(), indexRecord.getIrdHealthy());
    }
}
